<template>
  <div class="hello">
    <h1>24小时天气预报</h1>
    <div ref="chartContainer" class="chartContainer"></div>
  </div>
</template>

<script>
import axios from "axios";
import * as echarts from "echarts/core";
import { GridComponent } from "echarts/components";
import { LineChart } from "echarts/charts";
import { UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition]);
import { key, API_24H } from "@/common/constrant";
import { mapState, mapActions } from "vuex";
export default {
  // data() {
  //   return {
  //     hourly: [],
  //     hourlyWeatherDate: {
  //       fxTime: [],
  //       temp: [],
  //     },
  //   };
  // },
  computed: {
    ...mapState(["location", "hourly"]),
  },
  //监听器，监听状态的变化
  watch: {
    location: function () {
      // console.log("------")
      this.getDate(); //
    },
  },
  created() {
    this.getDate();
  },
  methods: {
    ...mapActions(["updateHourlyAction"]),
    getDate() {
      axios
        .get(API_24H, {
          params: {
            key,
            location: this.location.id,
          },
        })
        .then((res) => {
          console.log(res.data);
          let hourData = {
            fxTime: [],
            temp: [],
          };
          //需要把后台获取的数据存放到fxtime或temp中
          res.data.hourly.forEach((element) => {
            hourData.fxTime.push(element.fxTime);
            hourData.temp.push(element.temp);
          });
          this.updateHourlyAction(hourData);

          //调用初始化图表的方法
          this.initECharts(this.hourly.fxTime, this.hourly.temp);
        });
    },
    //初始化图表
    initECharts(xAxisData, seriesData) {
      var chartDom = this.$refs.chartContainer;
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        xAxis: {
          type: "category",
          data: xAxisData,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: seriesData,
            type: "line",
            label: {
              show: true,
            },
          },
        ],
      };
      option && myChart.setOption(option);
    },
  },
};
</script>

<style scoped>
.chartContainer {
  height: 300px;
}
</style>
